package com.wj.task;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.wj.pojo.Employee;
import com.wj.pojo.MailConstants;
import com.wj.pojo.MailLog;
import com.wj.service.IEmployeeService;
import com.wj.service.IMailLogService;
import org.springframework.amqp.rabbit.connection.CorrelationData;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import java.time.LocalDateTime;
import java.util.List;

/**
 * 邮件发送定时任务
 *
 * @Author wj
 * @Date 2022/7/22 17:37
 * @Description: TODO
 * @Version 1.0
 */
@Component
public class MailTask {

    @Resource
    private IMailLogService mailLogService;
    @Resource
    private IEmployeeService employeeService;
    @Resource
    private RabbitTemplate rabbitTemplate;

    /**
     * 邮件发送定时任务
     */
    @Scheduled(cron = "*/20 * * * * ?")
    public void mailTask() {
        List<MailLog> list = mailLogService.list(new QueryWrapper<MailLog>().eq("status", MailConstants.DELIVERING)
                .lt("tryTime", LocalDateTime.now()));

        list.forEach(mailLog -> {
            if (mailLog.getCount() >= MailConstants.MAX_TRY_COUNT) {
                //大于等于三次更新成发送失败
                mailLogService.update(new UpdateWrapper<MailLog>().set("status", MailConstants.FAILURE)
                        .eq("msgId", mailLog.getMsgId()));
            }
            //更新发送次数，时间
            mailLogService.update(new UpdateWrapper<MailLog>().set("count", mailLog.getCount() + 1)
                    .set("updateTime", LocalDateTime.now())
                    .set("tryTime", LocalDateTime.now().plusMinutes(MailConstants.MSG_TIMEOUT))
                    .eq("msgId",mailLog.getMsgId())
            );
            //获取员工信息重新发送
            List<Employee> employee = employeeService.getAllEmployeeById(mailLog.getEid());
            rabbitTemplate.convertAndSend(MailConstants.MAIL_EXCHANGE_NAME, MailConstants.MAIL_ROUTING_KEY_NAME
                    , employee.get(0), new CorrelationData(mailLog.getMsgId()));
        });
    }

}
